package controller

import (
    "encoding/json"
    "github.com/wubo19842008/gowxtks/server/config"
    "github.com/wubo19842008/gowxtks/server/token"
    "github.com/wubo19842008/gowxtks/utils"
    "io"
    "log"
    "net/http"
)

const (
    TICKET_GW_MP string = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?" +
        "type=jsapi&"
    TICKET_GW_CP string = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?"
)

type TicketCtrl struct {
    Config map[string]config.WxConfig
}

func (c *TicketCtrl) Get(rw http.ResponseWriter, req *http.Request) {
    log.Println(c.Config)
    req.ParseForm()
    aid := req.FormValue("aid")

    log.Printf("aid is %s", aid)
    io.WriteString(rw, token.GetTicket(aid))
}

func (c *TicketCtrl) Refresh(rw http.ResponseWriter, req *http.Request) {
    req.ParseForm()
    aid := req.FormValue("aid")
    log.Printf("aid is %s", aid)

    cfg := c.Config[aid]
    url := TICKET_GW_MP + "access_token=" + token.GetToken(aid)
    if cfg.WxType == config.WX_CP {
        url = TICKET_GW_CP + "access_token=" + token.GetToken(aid)
    }

    rr := utils.DoGet(url)
    var _ticket token.WxJsTicket
    json.Unmarshal(rr, &_ticket)
    token.SetTicket(aid, _ticket.Ticket)
    io.WriteString(rw, _ticket.Ticket)
}
